package com.backend.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.backend.system.beans.permission.ListPermissionByRoleReq;
import com.backend.system.beans.permission.ListPermissionByRoleVO;
import com.backend.system.common.PageBean;
import com.backend.system.dao.entity.Dictionary;
import com.backend.system.dao.entity.Permission;
import com.backend.system.dao.entity.RolePermission;
import com.backend.system.dao.mapper.PermissionMapper;
import com.backend.system.service.IDictionaryService;
import com.backend.system.service.IPermissionService;
import com.backend.system.service.IRolePermissionService;
import com.backend.system.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author backend-manage
 * @since 2024-04-02
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private IRolePermissionService rolePermissionService;

    @Resource
    private IDictionaryService dictionaryService;

    /**
     * 通过角色ID查角色对应的权限
     *
     * @param roleId 角色ID
     * @return 权限列表
     */
    @Override
    public List<Permission> getPermissionsByRoleId(Long roleId) {
        List<RolePermission> rolePermissions = rolePermissionService.getPermissionsByRoleId(roleId);
        Set<Long> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toSet());
        if (CollUtil.isEmpty(permissionIds)) {
            return Collections.emptyList();
        }
        return this.listByIds(permissionIds);
    }

    /**
     * 按角色查询全部权限（标识已拥有、未拥有）
     *
     * @param req 请求参数
     * @return 响应
     */
    @Override
    public PageBean<ListPermissionByRoleVO> listPermissionByRole(ListPermissionByRoleReq req) {
        // 查询当前角色已有的权限
        List<RolePermission> rolePermissions = rolePermissionService.getPermissionsByRoleId(req.getRoleId());
        Set<Long> permissionIds = rolePermissions.stream().map(RolePermission::getPermissionId).collect(Collectors.toSet());

        // 分页查全部权限
        IPage<Permission> page = new Page<>(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        // 按权限类型的asc排序
        queryWrapper.orderByAsc(Permission::getType);
        queryWrapper.orderByDesc(Permission::getCreateTime);
        IPage<Permission> permissionPage = this.getBaseMapper().selectPage(page, queryWrapper);

        // 处理查询结果
        List<Permission> records = permissionPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageBean<>();
        }

        // 权限类型映射处理
        Map<Integer, String> permissionTypeMap = Collections.emptyMap();
        Set<Integer> typeIdSet = records.stream().map(Permission::getType).filter(Objects::nonNull).collect(Collectors.toSet());
        if (CollUtil.isNotEmpty(typeIdSet)) {
            List<Dictionary> dictionaryList = dictionaryService.listByIds(typeIdSet);
            permissionTypeMap = dictionaryList.stream().collect(Collectors.toMap(dict -> dict.getId().intValue(), Dictionary::getDictVal));
        }

        final Map<Integer, String> finalPermissionTypeMap = permissionTypeMap;
        List<ListPermissionByRoleVO> resultList = records.stream().map(record -> ListPermissionByRoleVO.convert(record, permissionIds, finalPermissionTypeMap)).collect(Collectors.toList());
        return PageUtil.convertPage(permissionPage, resultList);
    }
}
